<?php
!defined('IN_ZHUSHOU') && exit('Access Denied');

class MessageModel extends CacheBaseModel
{
    // 消息表, 日后可以根据uid进行分表
    const NOTICE_TABLE = 'notices';
    const UNSEND_MSG = 'push:qid.msgnum:map';

    public function __construct()
    {
        parent::__construct();
    }

    public function addUnSend($qid)
    {
        // $redis = $this->getGlobalRedis();
        // $redis->hIncrBy(self::UNSEND_MSG, $qid, 1);
    }

    /**
     * 是否在通知栏显示push消息
     *
     * @return true/false
     */
    public function isPop($toQid, $msgType, $channel)
    {
        $runMode = strtoupper(RUN_MODE);
        $LimitDic  = Config::getInstance('msg')->getValue($runMode.'_PUSH_LIMT');
        $pushLimit = $LimitDic[$msgType];
        if(!isset($LimitDic[$msgType][$channel])) {
            return false;
        }

        $redis = $this->getIdcHashRedis($toQid);

        $userKey = "push:num:{$msgType}:{$toQid}";

        $num = intval($redis->incr($userKey));
        if($toQid == 148800088) {
            $num = 0;
        }

        if($num > $pushLimit['num']) {
            return false;
        }elseif($num == 1) {
            $redis->EXPIRE($userKey, $pushLimit['time']);
        }
        return true;
    }

    /**
     * 后台跑发送用户不在线时的消息
     * @return [type] [description]
     * @author lijie
     * @date   2015-05-28
     */
    public function cronPush($qid)
    {
        $qid = intval($qid);
        //$redis = $this->getGlobalRedis();
        // $msgNum = intval($redis->hGet(self::UNSEND_MSG, $qid));
        // if($msgNum <= 0) {
        //     return;
        // }

        $sql = 'SELECT * FROM notices WHERE  push_status=1 and to_uid='.$qid.' order by notice_id asc';
        $datas = $this->execute($sql);

        while ($row = $datas->fetchRow()) {
            $lock = $this->update(array('push_status' => 2), //set
                        array('notice_id' => intval($row['notice_id'])),  //where
                        self::NOTICE_TABLE);

            if(!$lock) {
                continue;
            } 

            $pushRes = $this->push($row['from_uid'], $row['to_uid'], $row['msg_type'], $row['notice_channel'],
                    $row['relate_id'], strtotime($row['notice_time']), $row['notice_id']);

            $pushSt = $this->getPushStatus($pushRes);

            if($pushSt >= 10) {
                $this->update(array('push_status' => $pushSt, 'push_time' => date('Y-m-d H:i:s')), //set
                        array('notice_id' => intval($row['notice_id'])),  //where
                        self::NOTICE_TABLE);
            }
        }

        //$redis->hSet(self::UNSEND_MSG, $qid, 0);
    }

   
    public function push($fromQid, $toQid, $msgType, $channel, $tid, $time, $msgid)
    {
        $pushData = array(
            "pstid" => 6588,
            "msgtype" => 6, 
            "content" => array(
                "type" => $msgType, 
                "channel" => $channel, 
                "tid" => $tid,
                'tip' => '',  
                'title' => '', 
                "time" => $time,
                'count' => 1,
                'msgId' => $msgid,
                'qid' => $toQid,
            ),
        );

        if($this->isPop($toQid, $msgType, $channel)) {
            if($msgType == 1) {
                $fromName = UserProxy::getUserNameByQid($fromQid);
                $pushData['content']['tip'] = '360手机助手应用圈';
                $pushData['content']['title'] = "{$fromName} 评论了你";
            }elseif($msgType == 5 && $channel == 6) {
                $fansCount = $this->getCount($toQid, 6, 0); //获取新粉丝数
                if($fansCount <= 0){
                    $fansCount = 1;
                }
                $pushData['content']['tip'] = '360手机助手应用圈';
                $pushData['content']['title'] = "你有{$fansCount}个新粉丝";
            }elseif($msgType == 2){
                $pushData['content']['tip'] = '360手机助手应用圈';
                $pushData['content']['title'] = "厉害咯，有人为你点赞";
            }
        }

        $pushSdk = new PushSdk();
        $pushRes = $pushSdk->pushByQid($toQid, json_encode($pushData));
        return $pushRes;
    }

    public function validateMsgType($channel, $subChannel, $noticeType, $msgType)
    {
        if($channel < 1  || $channel >7) {
            return false;
        }

        $channelTypeMap  = Config::getInstance('msg')->getValue('CHANNEL_TYPE_MAP');

        $type =  $channelTypeMap[$channel][$subChannel][$msgType];
        if(!isset($type) || $noticeType != $type) { //兼容老接口的$noticeType
            return false;
        }

        return true;
    }

    public function getPushStatus($pushRes)
    {
        $pushSt = 127;
        if($pushRes == -1) {
            $pushSt = 1;
        }elseif(is_array($pushRes)){
            $pushSt = intval($pushRes['result']) + 10;
        }
        return $pushSt;
    }

    // 发送消息, 注意用签名校验, 防止重放
    public function send($from, $to, $channel, $subChannel, $noticeType, $msgType, $relate, $subRelate)//, $pushSt)
    {
        // $ips = array('123.125.83.240', '10.121.214.10');
        // if(!in_array(Utility::getClientIp(), $ips)) {
        //     return;
        // }

        $noticeTime = date('Y-m-d H:i:s');
        $data = array(
            'from_uid' => $from, 
            'to_uid' => $to, 
            'notice_channel' => $channel, 
            'sub_channel' => $subChannel, 
            'msg_type' => $msgType, 
            'notice_type' => $noticeType, 
            'relate_id' => $relate, 
            'sub_relate_id' => $subRelate, 
            //'push_status' => $pushSt,
            'notice_time' => $noticeTime
        );
        // if($pushSt >= 10) { //已经push过的记录push时间
        //     $data['push_time'] = $noticeTime;
        // }
        $id = $this->add($data, self::NOTICE_TABLE);
        if (!$id) {
            $hostname = Utility::getHostName();
            CommentTool::sendLog('push_sdk_insert_error', "host={$hostname} data=".serialize($data));
        }
        return $id;
    }

    // 设定已读状态
    public function setPushData($id, $pushSt)
    {
        $sql = 'update ' . self::NOTICE_TABLE . ' SET push_time=\''.date('Y-m-d H:i:s').'\',push_status='.intval($pushSt)
             . ' WHERE notice_id='.intval($id);
        return $this->execute($sql);
    }

    /**
     * 验证消息逻辑
     *
     * @author lijie
     * @date   2015-05-12
     */
    public function validateMessage($from, $to, $channel, $subChannel, $noticeType, $msgType)
    {
        if(!$this->validateMsgType($channel, $subChannel, $noticeType, $msgType)) {
            return array('status' => -5, 'message' => 'Invalid Channel Or Type');
        }

        if ($from > 0) {
            $isValid = UserProxy::isValidQid($from);
            if (!$isValid) {
                return array('status' => -3, 'message' => 'From User Invalid');
            }
        }

        $isValid = UserProxy::isValidQid($to);
        if (!$isValid) {
            return array('status' => -4, 'message' => 'To User Invalid');
        }

        return array('status' => 1, 'message' => 'Ok');
    }


    // 获取个数
    public function getCount($to, $channel = 0, $status = -1)
    {
        $condition = array('where' => array('to_uid' => $to));
        if ($channel != 0)
        {
            $condition['where']['notice_channel'] = $channel;
        }

        if ($status > -1)
        {
            $condition['where']['status'] = $status;
        }

        $count = $this->count($condition, self::NOTICE_TABLE);
        return $count;
    }

    // 获取分组个数
    public function getGroupCount($to, $status = -1)
    {
        $statusSql = '';
        if ($status > -1)
        {
            $statusSql = ' And status=' . $status;
        }

        $sql        = 'SELECT notice_channel AS channel, COUNT(*) AS num FROM ' . self::NOTICE_TABLE . ' WHERE to_uid=' . $to . $statusSql . ' GROUP BY notice_channel';
        $result     = $this->getManyByQuery($sql);
        $groupCount = array();
        if (is_array($result))
        {
            foreach ($result as $item)
            {
                $groupCount[$item['channel']] = $item['num'];
            }
        }
        return $groupCount;
    }

    // 获取列表，获取未读消息列表直接从主库读
    public function getList($to, $channel = 0, $status = -1)
    {
        $channelSql = '';
        if ( is_numeric($channel) && $channel > 0 )
        {
            $channelSql = ' AND notice_channel = ' . intval($channel);
        }
        $statusSql = '';
        if (is_numeric($status) && $status >= 0)
        {
            $statusSql = ' AND status = ' . intval($status);
        }
        $sql  = '/*master*/ SELECT notice_id,from_uid,to_uid,notice_channel,relate_id,notice_time,status,msg_type,notice_type,sub_channel,sub_relate_id
                 FROM ' . self::NOTICE_TABLE . ' WHERE to_uid=' . intval($to) . $channelSql . $statusSql. ' order by notice_id desc limit 100';
        $list = $this->getManyByQuery($sql);
        return $list;
    }

    // 设定已读状态
    public function setRead($ids)
    {
        if (is_array($ids) && sizeof($ids) > 0)
        {
            $sql = 'Update ' . self::NOTICE_TABLE . ' SET status=1 WHERE notice_id IN (' . implode(',', $ids) . ')';
            $this->execute($sql);
        }
        return True;
    }

    // 根据回复或者评论ID获取app的信息
    public function getAppInfos($commentIds)
    {
        $sql = 'SELECT object_id, comment_id FROM comment_meta WHERE comment_id in (' . implode(',' , $commentIds) . ')';
        $items = $this->getManyByQuery($sql);
        $pair = array();
        $sids = array();
        if (is_array($items) && sizeof($items) > 0)
        {
            foreach ($items as $item)
            {
                $pair[$item['comment_id']] = $item['object_id'];
                $sids[$item['object_id']] = 1;
            }
            $sids = implode('|', array_keys($sids));
            $url  = 'http://openbox.mobilem.360.cn/index/getSoftInfoByIdsAccordingToFields/sids/' . $sids . '/fields/soft_id%7Csoft_name%7Clogo_url%7Cpname';
            $json = Utility::getUrlContents($url, 3);
            $apps = json_decode($json, True);
            foreach ($pair as $commentId => $sid)
            {
                if (isset($apps[$sid]))
                {
                    $pair[$commentId] = $apps[$sid];
                }
            }
        }
        return $pair;
    }

    // 根据推荐ID获取话题信息
    public function getTopics($rids)
    {
        if (RUN_MODE == 'test')
        {
            $host = '123.125.83.240';
            $header = array('Host:openbox.mobilem.360.cn');
        }
        else
        {
            $host = 'openbox.mobilem.360.cn';
            $header = array();
        }
        $url = 'http://' . $host . '/topic/getTopicByRecommid?recomm_ids=' . implode(',', $rids);
        $json = Utility::getUrlContents($url, 3, $header);
        $topics = json_decode($json, True);
        if (is_array($topics) && isset($topics['status']) && $topics['status'] == 1)
        {
            $topics = $topics['topic'];
        }
        return $topics;
    }

    // 调用林哲接口, 获取用户分享的app
    public function getShares($sids, $channel = 3)
    {
        if (RUN_MODE == 'test')
        {
            $host = '123.125.83.240';
            $header = array('Host:openbox.mobilem.360.cn');
        }
        else
        {
            $host = 'openbox.mobilem.360.cn';
            $header = array();
        }
        $url    = 'http://' . $host . '/daren/getRecomm?recomm_ids=' . implode(',', $sids);
        if($channel > 0) {
            $url .= '&channel=' . $channel;
        }
        $json   = Utility::getUrlContents($url, 3, $header);
        $return = json_decode($json, True);
        $shares = array();
        if (is_array($return) && isset($return['status']) && $return['status'] == 1)
        {
            $shares = $return['share'];
        }
        return $shares;
    }

    public function getMessage($notices)
    {
        if(empty($notices)) {
            return array();
        }

        $keys = array("notice_id", "from_uid","to_uid","notice_channel","relate_id",
            "msg_type","notice_type","sub_channel","sub_relate_id");
        $params = array();
        foreach ($notices as $i => $notice) {
            if($notice['notice_channel'] == 1) {
                continue;
            }
            foreach ($keys as $key) {
                $params[$i][$key] = $notice[$key];
            }
        }

        if (RUN_MODE == 'test') {
            $host = '123.125.83.240';
            $header = array('Host:openbox.mobilem.360.cn');
        }  else {
            $host = 'openbox.mobilem.360.cn';
            $header = array();
        }
        $url    = 'http://' . $host . '/notice/getContent';
        $json   = Utility::post($url, array('message' => $params), 3, $header);
        // $url    = 'http://test.comment.mobilem.360.cn/msg/post';
        // $json   = Utility::post($url, array('msg' => $params), 3);
        $return = json_decode($json, True);
        $data = array();
        if (is_array($return) && isset($return['status']) && $return['status'] == 1)
        {
            $data = $return['data'];
        }
        return $data;
    }
}
